/**
 * @author  RR42 <im.razzy@gmail.com>
 * @version 0.1.1
 *
 * @section LICENSE
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details at
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @section DESCRIPTION
 *
 * This is a GTK+2 su frontend
 */

#include <stdlib.h>
#include <gtk/gtk.h>
#include <string.h>
#include <pty.h>
#include "librr42su.h"

#define SU_PROGRAM "su"
#define SU_REDIRECT "/usr/libexec/rr42su/suredirect"

char **cmdargs = NULL;

/**
  * This prints help message
  * @author RR42
  */

void g_print_help() {
    g_print("USAGE: rr42su [su args]\n"
            "\n"
"This program simple su frontend. It hasn't full su functionality.\n"
"It gets only password from user (and gives it to su).\n"
"\n"
"This should work: rr42su -c \"urxvt -e htop\" (urxvt is X terminal\n"
"emulator, htop is system monitor, \"-e\" is urxvt option). I have\n"
"pointed to urxvt in example because I'm big fan of it.\n"
"\n"
"Author's aim was reinventing the wheel, this program is distributed\n"
"in the hope that it will be useful, but WITHOUT ANY WARRANTY, it was\n"
"made just for fun, blablabla\n"
"\n"
"Please, report bugs to https://code.google.com/p/rr42su/issues/list\n");
}

/**
 * This runs su
 * @author RR42
 * @return nothing. FIXME
 * 
 * @section TODO
 */

int rr42su_run() {
    int fd;
    pid_t pid;

    pid = forkpty(&fd, 0, 0, 0);
    if (pid == 0) { // Forked process goes there:
        if (execvp(cmdargs[0], cmdargs) == -1) {
            gmessage("ERROR");
        }
    } else if (pid == -1) {
        // Error
        return 1;
    } else { // Parent process goes there        
        rr42su_ask_password_and_write(fd);
        
        // su become a responsible for the outputting
        char arg[20];
        snprintf(arg, 20, "%d", fd);
        char **cmdargs = (char**)malloc(3*sizeof(char*));
        cmdargs[0] = strdup(SU_REDIRECT); // FIXME: Is strdup necessary?
        cmdargs[1] = strdup(arg);
        cmdargs[2] = NULL;
        execvp(cmdargs[0], cmdargs);
    }
    return 0;
}

int main (int argc, char *argv[]) {
    gtk_init(&argc, &argv);
    if (argc <= 1 ) { //TODO: command line options
        g_print_help();
        return 0;
    }

    cmdargs = (char**)realloc(cmdargs, (argc+1)*sizeof(char*));
    memcpy(&cmdargs[0], &argv[0], (argc)*sizeof(char*));
    cmdargs[0] = SU_PROGRAM;
    cmdargs[argc] = NULL;

    rr42su_run();

    return 0;
}
